package com.example.webservice.service.impl;

import com.example.webservice.entity.ApiValue;
import com.example.webservice.entity.KPIReq;
import com.example.webservice.entity.KpiRes;
import com.example.webservice.entity.ReqApi;
import com.example.webservice.service.IKpiService;
import com.example.webservice.service.KpiWebService;
import com.example.webservice.util.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.util.ArrayList;
import java.util.List;

@WebService
@Service
@Slf4j
public class KpiWebServiceImpl implements KpiWebService {

    @Autowired
    IKpiService iKpiService;

    @WebMethod
    @WebResult(name = "resultName")
    @Override
    public String getKPIValue(@WebParam(name = "param") String param) {
        param = param.replaceAll("＜", "<");
        param = param.replaceAll("＞", ">");
//        System.out.println("param=#" + param + "#");
        log.info("WebService服务getKPIValue接受到的参数：\n{}",param);
        // 将字符串格式的xml请求转化为对象
        KPIReq requestXml = (KPIReq) XmlUtils.xmlStrToObject(KPIReq.class, param);

        KpiRes res=new KpiRes();
        res.setStatus("success");
        res.setMessage("");
        List<ApiValue> apiValueList=new ArrayList<>();
        res.setApi(apiValueList);

        //得到指标列表
        List<ReqApi> apiList = requestXml.getApi();
        //指标查询是否异常标识
        int flag=0;
        //遍历指标列表，得到指标值
        for (ReqApi kpi : apiList) {
            String value=null;
            try {
                long begin = System.currentTimeMillis();
//                value=iKpiService.getKpiValue(kpi.getName());
                // 获取返回数据
//                value=webserviceService.get(kpi.getName());
                value = kpi.getName();
                long end = System.currentTimeMillis();
                log.info("{}={};用时:{}",kpi,value,(end-begin));
            }catch (Exception e){
                res.setStatus("failure");
                res.setMessage("系统异常");
                res.setReason("获得"+kpi+"指标异常");
                res.setApi(null);
                flag=1;
                e.printStackTrace();
            }
            //flag=1，表示出现异常，返回错误
            if(flag==1)
                break;
            apiValueList.add(new ApiValue(kpi.getName(),value));
        }

        //将对象转为xml字符串返回
        String xmlStr = XmlUtils.objectToXmlStr(res, res.getClass());
        xmlStr = xmlStr.replaceAll("standalone=\"yes\"", "");
        log.info("WebService服务getKPIValue返回的结果：\n{}",xmlStr);
        return xmlStr;
    }

    @WebMethod
    @WebResult(name = "resultName")
    @Override
    public String getStatus(@WebParam(name = "param") String param) {
        return String.valueOf(0);
    }
}
